package com.enjoy.spring.starter.redisspringbootstarter;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
@ConditionalOnClass(Redisson.class)
@EnableConfigurationProperties(RedissonPropterties.class)
public class RedissonAutoConfiguration {
    @Bean
    RedissonClient redissonClient(RedissonPropterties redissonPropterties){
        Config config = new Config();
        String prefix = "redis://";
        if (redissonPropterties.isSsl()){
            prefix = "rediss://";
        }
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(prefix+redissonPropterties.getHost()
        +":"+redissonPropterties.getPort())
                .setConnectTimeout(redissonPropterties.getTimeout());
        if(!StringUtils.isEmpty(redissonPropterties.getPassword())){
            singleServerConfig.setPassword(redissonPropterties.getPassword());
        }
        return Redisson.create(config);
    }
}
